package fidel.spring.shiro.demo.controller;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import fidel.spring.shiro.demo.exception.CustomException;
import fidel.spring.shiro.demo.po.ActiveUser;
import fidel.spring.shiro.demo.po.SysUser;
import fidel.spring.shiro.demo.realm.CustomRealm;

/**
 * 
 * Description: 登录和退出
 * 
 * @version 1.0
 */
@Controller
public class HandlerController {

    /**
     * 处理用户的登录请求
     * 
     * @return 视图名称
     * @throws CustomException
     */
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, SysUser sysUser, String rememberMe,
        // 用户输入的验证码
        @RequestParam(value = "randomcode", required = false) String inputValue) throws CustomException {
        HttpSession session = request.getSession();
        // 判断主体是否已认证，它与是否被记住（isRemembered）不同，后者并不意味着主体通过了身份验证
        if (SecurityUtils.getSubject().isAuthenticated()) {
            // 重定向请求至另一地址
            return "redirect:/index.action";
        }
        // 如果请求方式为get
        if (request.getMethod().equals("GET")) {
            // 转发到视图名称为login的页面
            return "login";
        }
        // 从会话中获取的验证码
        String captcha = (String) session.getAttribute("validateCode");
        // 如果用户输入的验证码为空
        if (!StringUtils.hasText(inputValue)) {
            throw new CustomException("输入的验证码无效");
        }
        if (!captcha.equals(inputValue)) {
            throw new CustomException("验证码错误");
        }
        // 获取主体
        Subject subject = SecurityUtils.getSubject();
        // 获取用户的帐号和密码
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUsercode(), sysUser.getPassword());
        // 如果rememberMe的值不为空且等于on
        token.setRememberMe(StringUtils.hasText(rememberMe) && rememberMe.equals("on"));
        subject.login(token);
        ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
        session.setAttribute("activeUser", activeUser);
        return "redirect:/index.action";
    }

    // 系统首页
    @RequiresPermissions("user:inquire")
    @RequestMapping("/index")
    public String first() throws Exception {
        return "homepage";
    }

    // 清除与指定账户身份相关的任何缓存数据
    @RequestMapping(value = "/clearCache", method = RequestMethod.GET)
    public String clearCache() {
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        // 获取安全管理器的所有realm
        Collection<Realm> realms = securityManager.getRealms();
        for (Realm realm : realms) {
            if (realm instanceof CustomRealm) {
                ((CustomRealm) realm).clearCache();
            }
        }
        return "success";
    }

}
